﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Prism.Services.Dialogs;
using System.Collections.ObjectModel;
using WPF.Core;
using WPF.Core.Dtos;
using WPF.Core.Services;

namespace WPF.ToDo.ViewModels
{
    public partial class ToDoViewModel : NavigateViewModel
    {
        private readonly IToDoService appService;
        private readonly IDialogService dialog;

        [ObservableProperty]
        private ToDoPagingInfo paging;

        [ObservableProperty]
        private ObservableCollection<ToDoModel> gridModelList;

        public ToDoViewModel(IToDoService appService, IDialogService dialog)
        {
            this.appService = appService;
            this.dialog = dialog;
            Paging = new ToDoPagingInfo()
            {
                PageNumber = 1,
                PageSize = 1,
            };
            GridModelList = new ObservableCollection<ToDoModel>();
        }

        [RelayCommand]
        private async Task Search()
        {
            await GetAllAsync();
        }

        [RelayCommand]
        private void Add()
        {
            dialog.ShowDialog("CreateToDoView", async callBack =>
            {
                if (callBack.Result == ButtonResult.OK)
                    await GetAllAsync();
            });
        }

        [RelayCommand]
        private void Edit(ToDoModel model)
        {
            DialogParameters param = new DialogParameters();
            param.Add("Value", model);

            dialog.ShowDialog("CreateToDoView", param, async callBack =>
            {
                if (callBack.Result == ButtonResult.OK)
                    await GetAllAsync();
            });
        }

        [RelayCommand]
        private async Task Delete(ToDoModel model)
        {
            await appService.Delete(model.Id);
            var todo = GridModelList.FirstOrDefault(t => t.Id == model.Id);
            if (todo != null)
                GridModelList.Remove(todo);
        }

        [RelayCommand]
        private async Task Pageing()
        {
            await GetAllAsync();
        }

        /// <summary>
        /// 获取所有待办事项
        /// </summary>
        /// <returns></returns>
        private async Task GetAllAsync()
        {
            var models = await appService.GetAll(Paging);

            GridModelList.Clear();

            if (models != null)
            {
                foreach (var model in models)
                {
                    GridModelList.Add(model);
                }
            }
        }
    }
}
